import React from "react";
import User from "@/service/user-service.jsx";
import Mutils from "@/utils/index.jsx";

const _user = new User();
const _mm = new Mutils();

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: "",
      redirect: _mm.getUrlParam("redirect") || "/"
    };
  }
  componentWillMount(){
	  document.title = '登录 -IMOOC Admin'
  }
  handleInputChange(e) {
    const { name, value } = e.target;
    this.setState({
      [name]: value
    });
  }
  handleSubmit() {
    const { username, password } = this.state;
    const checkResult = _user.checkLoginInfo(username, password);
    if (checkResult.status) {
      _user
        .login({
          username,
          password
        })
        .then(
          res => {
			localStorage.setItem('userInfo',JSON.stringify(res.data))
            this.props.history.push(this.state.redirect);
          },
          errMsg => {
            _mm.errorTips(errMsg);
          }
        );
    } else {
      _mm.errorTips(checkResult.msg);
    }
  }
  handleKeyup(e){
	if(e.keyCode === 13){
		this.handleSubmit()
	}
  }
  render() {
    return (
      <div className="login-wrapper">
        <div className="col-md-4 col-md-offset-4">
          <div className="panel panel-default" style={{ marginTop: "30%" }}>
            <div className="panel-heading">欢迎登录 IMOOC MALL</div>
            <div className="panel-body">
              <div className="form">
                <div className="form-group">
                  <label htmlFor="username">用户名：</label>
                  <input
                    type="text"
                    className="form-control"
					onChange={e => this.handleInputChange(e)}
					onKeyUp={(e) => this.handleKeyup(e)}
                    id="username"
                    name="username"
                  />
                </div>
                <div className="form-group">
                  <label htmlFor="password">密码：</label>
                  <input
                    type="password"
                    className="form-control"
					onChange={e => this.handleInputChange(e)}
					onKeyUp={(e) => this.handleKeyup(e)}
                    id="password"
                    name="password"
                  />
                </div>
                <button
                  onClick={() => this.handleSubmit()}
                  className="btn btn-lg btn-primary btn-block"
                >
                  登录
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Login;
